package com.trg.flex.frm.validation
{
	import mx.validators.NumberValidator;
	import mx.validators.ValidationResult;

	public class ExtNumberValidator extends NumberValidator
	{
		public function ExtNumberValidator()
		{
			super();
		}
		
		/**
		 * This does all regular number validation and the validation added by
		 * ExtNumberValidator.
		 */
		public static function validateNumber(validator:ExtNumberValidator,
										  value:Object,
										  baseField:String):Array {
	    	var result:Array = NumberValidator.validateNumber(validator, value, baseField);
	    	
			if (result.length != 0)
				return result;
			else
				return validateExt(validator, value, baseField);
	    }
	    
	    /**
	     * This only does the validation that is added by ExtNumberValidator,
	     * i.e. maxIntegerDigits
	     */
	    protected static function validateExt(validator:ExtNumberValidator,
										  value:Object,
										  baseField:String):Array {
			var result:Array = [];
			
			if (validator.maxIntegerDigits != null) {
				var input:String = String(value);
				var pos:int = input.indexOf(validator.decimalSeparator);
				if (pos > -1)
					input = input.substr(0, pos);
				var regEx:RegExp = new RegExp(validator.thousandsSeparator, "g");
				input = input.replace(regEx, '');
				if (input.length > validator.maxIntegerDigits) {
					result.push(new ValidationResult(
						true, baseField, "integerDigits",
						validator.integerDigitsError != null ? validator.integerDigitsError : "The amount entered has too many digits before the decimal point."));
				}
			}
			
			return result;		
		}
		
		
		public var maxIntegerDigits:Object;
		
		public var integerDigitsError:String;
		
		override protected function doValidation(value:Object):Array {
	        var results:Array = super.doValidation(value);
			
			// Return if there are errors
			// or if the required property is set to <code>false</code> and length is 0.
			var val:String = value ? String(value) : "";
			if (results.length > 0 || ((val.length == 0) && !required))
				return results;
			else
			    return ExtNumberValidator.validateExt(this, value, null);
		}
		
	}
}